package other.socket;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Client extends JFrame {
    private Socket socket;
    private JTextArea chatArea;
    private JTextField inputField;
    private JButton sendButton;
    private PrintWriter writer;

    public Client() {
        super("Chat Client");
        try {
            System.out.println("正在连接服务端");
            socket = new Socket("localhost", 8088);
            System.out.println("服务端连接成功");

            // 初始化组件
            chatArea = new JTextArea(15, 30);
            chatArea.setEditable(false);
            inputField = new JTextField(20);
            sendButton = new JButton("发送");

            // 设置布局
            setLayout(new BorderLayout());
            add(new JScrollPane(chatArea), BorderLayout.CENTER);
            JPanel panel = new JPanel();
            panel.add(inputField);
            panel.add(sendButton);
            add(panel, BorderLayout.SOUTH);

            // 处理发送按钮的点击事件
            sendButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    sendMessage(inputField.getText());
                    inputField.setText("");
                }
            });

            // 启动接收消息的线程
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.start();

            // 获取输出流并设置为自动刷新
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            writer = new PrintWriter(bw, true);

            // 请求昵称
            requestNickname();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void requestNickname() {
        String nickName = JOptionPane.showInputDialog(this, "请输入昵称:");
        if (!nickName.trim().isEmpty()) {
            writer.println(nickName); // 将昵称发给服务端
        } else {
            JOptionPane.showMessageDialog(this, "昵称不能为空");
            requestNickname(); // 递归请求直到获得有效昵称
        }
    }

    private void sendMessage(String message) {
        if ("exit".equalsIgnoreCase(message)) {
            System.exit(0);
        }
        writer.println(message); // 发送数据到服务端
    }

    private class ServerHandler implements Runnable {
        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while ((message = br.readLine()) != null) {
                    chatArea.append(message + "\n"); // 将服务端发送过来的消息输出
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            Client client = new Client();
            client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            client.pack();
            client.setVisible(true);
        });
    }
}
